package com.study.algorithm.bag;

import java.util.Iterator;

/**
 * 包的实现
 * 包只有add方法，没有删除方法
 * Created by hui_stone on 2017/9/11 0011.
 */
public class Bag<Item> implements Iterable<Item>{

    private Node first; //链表的首结点
    private int N;

    private class Node {
        Item item;
        Node next;
    }

    public void add(Item item){

        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        N++;
    }

    public int count(){
        return N;
    }
    @Override
    public Iterator iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item>{

        private Node current = first;

        @Override
        public boolean hasNext() {
            return current !=null;
        }

        @Override
        public Item next() {

            Item item = current.item;
            current = current.next;
            return item;
        }

    }

    @Override
    public String toString() {

        String result = "";
        for(Item item : this){
            result += item + " ";
        }
        return result;
    }

    public static void main(String[] args) {

        Bag<String> bag = new Bag<String>();
        bag.add("a");
        bag.add("b");
        bag.add("c");
        bag.add("d");//new add
        bag.add("e");
        bag.add("f");
        bag.add("g");

        System.out.println("===== "+bag.N+" =============");
        System.out.println(bag);

    }

}
